﻿using Microsoft.Web.Administration;
using System;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net.NetworkInformation;
using System.Windows.Forms;

namespace WINBASE
{
    public partial class frmFmul : Form
    {
        ModifyRegistry myReg = new ModifyRegistry();
        DataTable dtConfig = new DataTable("IIS_Config");
        string strLoginUserId = "";
        string strWebSite = "";
        string strSite = "";
        string strConStr = "";
        string strLoginPwd = "";

        public frmFmul()
        {
            InitializeComponent();
            this.Text = System.Windows.Forms.Application.ProductName + " Login";
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Application.Exit();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(strWebSite) & !string.IsNullOrEmpty(strSite))
            {
                if (chkSaveSetting.Checked)
                {
                    myReg.Write("Website", strWebSite);
                    myReg.Write("Site", strSite);
                }

                strLoginUserId = txtUserId.Text.Trim();
                strLoginPwd = txtPwd.Text.Trim();
                int userCnt = (int)ApplicationService.QueryHelper.GetAVal("SELECT COUNT(*) FROM rcus1 WHERE UserId = @s AND ISNULL(Pwd,'') = @s", 
                                                                    strLoginUserId, strLoginPwd);

                if (userCnt > 0)
                {
                    ApplicationData.UserId = strLoginUserId;
                    ApplicationData.UserName = ApplicationService.QueryHelper.GetAVal("SELECT TOP 1 [User Name] FROM vw_rcus1 WHERE [User Id] = @s",strLoginUserId).ToString();
                    if (chkSaveSetting.Checked)
                    {
                        myReg.Write("LoginName", strLoginUserId);
                    }

                    ApplicationService.QueryHelper.ExecSql("INSERT INTO [dbo].[rclh1]([UserId],[ComputerName],[LoginDate],[StatusCode])" +
                                                                                 "VALUES(@s,@s,@s,@s)", 
                                                                                 strLoginUserId, System.Net.Dns.GetHostName(), DateTime.Now, "LIN");
                    ApplicationData.LoginTrxNo = (int)ApplicationService.QueryHelper.GetAVal("SELECT MAX(TrxNo) FROM rclh1 WHERE UserId = @s", strLoginUserId);


                    ApplicationData.InitializeData();
                    ApplicationObject.InitializeObject();
                    this.Hide();
                    ApplicationObject.FrmMain.Show();
                }
                else
                {
                    MessageBox.Show("Invalid User, Please make sure your User Name and Password!", "User Name or Password Incorrect", 
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    txtUserId.Focus();
                    txtUserId.SelectAll();
                }
            }
        }

        private void frmFmul_Load(object sender, EventArgs e)
        {
            this.SuspendLayout();

            dtConfig.Columns.Add("Key", typeof(string));
            dtConfig.Columns.Add("Value", typeof(string));

            if (myReg.ValueCount() > 0)
            {
                strLoginUserId = myReg.Read("LoginName");
                strWebSite = myReg.Read("Website");
                strSite = myReg.Read("Site");
            }

            if (!string.IsNullOrEmpty(strWebSite))
            {
                txtUserId.Text = strLoginUserId;
                txtWebsite.Text = strWebSite;
                txtWebsite_KeyDown(null, new KeyEventArgs(Keys.Enter));
                if (!string.IsNullOrEmpty(strSite))
                {
                    cboSite.Text = strSite;
                }
            }

            this.ResumeLayout();
        }

        private void txtWebsite_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode) {
			case Keys.Enter:
				string Website = txtWebsite.Text.Trim();
				if (!string.IsNullOrEmpty(Website)) {
					if (PingHost(Website, 2)) {
						bool isValidSite = false;
						bool isValidApp = false;

						ServerManager myWebSrv = null;
						Microsoft.Web.Administration.Application myDefaultApp = null;

						Site myDefaultSite = null;
						try {
							myWebSrv = ServerManager.OpenRemote(Website);
							foreach (Site mySite in myWebSrv.Sites) {
								if (mySite.Name == "Default Web Site") {
									myDefaultSite = mySite;
									isValidSite = true;
									break; // TODO: might not be correct. Was : Exit For
								}
							}

							if (isValidSite) {
								if (myDefaultSite.Applications.Count > 0) {
                                    foreach (Microsoft.Web.Administration.Application myApp in myDefaultSite.Applications)
                                    {
										if (myApp.Path == "/SysfreightWS") {
											myDefaultApp = myApp;
											isValidApp = true;
											break; // TODO: might not be correct. Was : Exit For
										}
									}
								}
							}
						} catch (Exception ex) {
							MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButtons.OK, MessageBoxIcon.Error);
							System.Diagnostics.Debugger.Break();
						}

						if (isValidSite & isValidApp) {
							ConfigurationSection myAppConfig = myDefaultApp.GetWebConfiguration().GetSection("appSettings");
							ConfigurationElementCollection myConfigElements = myAppConfig.GetCollection();

							foreach (ConfigurationElement myConfig in myConfigElements) {
								string key = myConfig.Attributes["Key"].Value.ToString();
								string value = myConfig.Attributes["Value"].Value.ToString();
								dtConfig.Rows.Add(key, value);
							}

                            string strDB = (from n in dtConfig.AsEnumerable()
                                            where n.Field<string>("Key") == "DataBase"
                                            select n.Field<string>("Value")).FirstOrDefault();
							cboSite.Items.AddRange(strDB.Split(','));
							if (cboSite.Items.Count > 0) {
								cboSite.SelectedIndex = 0;
							}
						}
					}
				}
				break;
		    }
        }

        public static bool PingHost(string nameOrAddress, int timeout)
        {
            bool pingable = false;
            Ping pinger = new Ping();
            try
            {
                PingReply reply = pinger.Send(nameOrAddress, timeout);
                pingable = reply.Status == IPStatus.Success;
            }
            catch (PingException ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return pingable;
        }

        private void cboSite_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cboSite.Text))
            {
                string strSelDB = (from n in dtConfig.AsEnumerable()
                                   where n["Key"].ToString() == cboSite.Text
                                   select n).FirstOrDefault()["Value"].ToString();

                if (strSelDB != null | !string.IsNullOrEmpty(strSelDB))
                {
                    string[] dbProperties = strSelDB.Split(',');
                    dynamic conSchemaName = dbProperties[dbProperties.Count() - 1];
                    string conSchema = (from n in dtConfig.AsEnumerable()
                                        where n.Field<string>("Key") == conSchemaName
                                        select n).FirstOrDefault()["Value"].ToString();
                    if (!string.IsNullOrEmpty(conSchema))
                    {
                        string strDataSource = dbProperties[0];
                        string strCatalog = dbProperties[1];
                        string strUserName = dbProperties[2];
                        string strPassword = dbProperties[3];

                        strConStr = conSchema.Replace("#DataSource", strDataSource);
                        strConStr = strConStr.Replace("#Catalog", strCatalog);
                        strConStr = strConStr.Replace("#UserName", strUserName);
                        strConStr = strConStr.Replace("#Password", strPassword);
                        SqlConnection tstCon = new SqlConnection();
                        if (!Utils.DBHelper.QueryHelper.IsValidConnection(strConStr, ref tstCon))
                        {
                            cboSite.SelectedIndex = -1;
                            strWebSite = "";
                            strSite = "";
                        }
                        else
                        {
                            strWebSite = txtWebsite.Text.Trim();
                            strSite = cboSite.Text;
                            ApplicationService.QueryHelper.Connection.ConnectionString = strConStr;
                        }
                    }
                    else
                    {
                        try
                        {
                            throw new InvalidCastException();
                        }
                        catch (InvalidCastException ex)
                        {
                            MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            cboSite.SelectedIndex = -1;
                        }
                    }
                }
                else
                {
                    try
                    {
                        throw new InvalidCastException();
                    }
                    catch (InvalidCastException ex)
                    {
                        MessageBox.Show(ex.Message, ex.GetType().FullName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        cboSite.SelectedIndex = -1;
                    }
                }
            }
        }

        SqlConnection _DBConnection = new SqlConnection();
        public SqlConnection DBConnection
        {
            get { return _DBConnection; }
        }

        private void frmFmul_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    System.Windows.Forms.Application.Exit();
                    break;
                default: break;
            }
        }

        private void txtPwd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnLogin_Click(null, null);    
            }
        }

        private void txtUserName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtPwd.Focus();
            }
        }
    }
}